<template>
  <PageContainer>
    <div class="library-page">
      <div class="library-header">
        <h1 class="page-title">素材库</h1>
        <p class="page-description">管理和浏览您的图片素材，支持智能搜索和筛选</p>
        
        <!-- 统计信息 -->
        <div class="stats-bar">
          <div class="stat-item">
            <span class="stat-value">{{ statistics.totalImages }}</span>
            <span class="stat-label">总图片数</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.formattedSize }}</span>
            <span class="stat-label">总大小</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.aiRecognitionSuccess }}</span>
            <span class="stat-label">AI识别成功</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ selectedImages.length }}</span>
            <span class="stat-label">已选择</span>
          </div>
        </div>
      </div>
      
      <div class="library-content">
        <!-- 侧边栏筛选器 -->
        <div class="library-sidebar">
          <SearchFilter
            ref="searchFilterRef"
            :popular-tags="popularTags"
            :loading="loading"
            @search="handleSearch"
            @get-suggestions="handleGetSuggestions"
            @load-popular-tags="handleLoadPopularTags"
          />
        </div>
        
        <!-- 主内容区 -->
        <div class="library-main">
          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <el-button 
                type="primary" 
                :icon="Upload"
                @click="goToUpload"
              >
                上传图片
              </el-button>
              
              <el-button 
                v-if="selectedImages.length > 0"
                type="success" 
                :icon="Edit"
                @click="batchGenerateText"
              >
                批量生成文案 ({{ selectedImages.length }})
              </el-button>
              
              <el-button 
                v-if="selectedImages.length > 0"
                type="warning" 
                :icon="CopyDocument"
                @click="batchExpandImages"
              >
                批量扩展 ({{ selectedImages.length }})
              </el-button>
              
              <el-button 
                v-if="selectedImages.length > 0"
                type="danger" 
                :icon="Delete"
                @click="batchDeleteImages"
              >
                批量删除 ({{ selectedImages.length }})
              </el-button>
            </div>
            
            <div class="toolbar-right">
              <el-button 
                v-if="selectedImages.length > 0"
                text
                @click="clearSelection"
              >
                取消选择
              </el-button>
              
              <el-button 
                text
                @click="selectAll"
                v-if="images.length > 0 && selectedImages.length < images.length"
              >
                全选
              </el-button>
              
              <span class="result-count">
                共 {{ pagination.totalElements }} 张图片
              </span>
            </div>
          </div>
          
          <!-- 图片网格 -->
          <ImageGrid
            :images="images"
            :loading="loading"
            :empty-message="emptyMessage"
            @image-click="handleImageClick"
            @preview="handlePreview"
            @generate-text="handleGenerateText"
            @expand-image="handleExpandImage"
            @delete="handleDeleteImage"
            @tag-click="handleTagClick"
            @show-all-tags="handleShowAllTags"
          />
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="pagination.totalPages > 1">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[12, 24, 48, 96]"
              :total="pagination.totalElements"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
      
      <!-- 图片预览对话框 -->
      <el-dialog
        v-model="previewVisible"
        title="图片预览"
        width="80%"
        :before-close="handleClosePreview"
      >
        <ImagePreview
          v-if="previewImage"
          :image="previewImage"
          @generate-text="handleGenerateText"
          @expand-image="handleExpandImage"
          @delete="handleDeleteImage"
          @tag-click="handleTagClick"
        />
      </el-dialog>
      
      <!-- 标签详情对话框 -->
      <el-dialog
        v-model="tagsVisible"
        title="所有标签"
        width="60%"
      >
        <div class="all-tags-container" v-if="currentImageTags">
          <el-tag
            v-for="tag in currentImageTags"
            :key="tag"
            class="tag-item"
            @click="handleTagClick(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Edit, Delete, CopyDocument } from '@element-plus/icons-vue'
import PageContainer from '@/components/layout/PageContainer.vue'
import SearchFilter from '@/components/library/SearchFilter.vue'
import ImageGrid from '@/components/library/ImageGrid.vue'
import ImagePreview from '@/components/library/ImagePreview.vue'
import { imageApi } from '@/api/image'
import { searchApi } from '@/api/search'
import type { 
  ImageModel, 
  SearchCriteria, 
  SearchSuggestion, 
  TagCloudItem,
  PaginatedResponse,
  Statistics
} from '@/types'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const images = ref<ImageModel[]>([])
const selectedImages = ref<ImageModel[]>([])
const popularTags = ref<TagCloudItem[]>([])
const currentPage = ref(1)
const pageSize = ref(24)
const searchCriteria = ref<SearchCriteria>({})
const previewVisible = ref(false)
const previewImage = ref<ImageModel | null>(null)
const tagsVisible = ref(false)
const currentImageTags = ref<string[]>([])
const searchFilterRef = ref()

// 防止重复请求的标志
const isLoadingImages = ref(false)
const isLoadingStats = ref(false)
const isLoadingTags = ref(false)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  totalPages: 1,
  totalElements: 0,
  size: 24,
  hasNext: false,
  hasPrevious: false
})

// 统计信息
const statistics = reactive<Statistics>({
  totalImages: 0,
  totalSize: 0,
  formattedSize: '0 B',
  jpegCount: 0,
  pngCount: 0,
  gifCount: 0,
  webpCount: 0,
  popularTags: [],
  recentUploads: 0,
  aiRecognitionSuccess: 0,
  textGenerationSuccess: 0,
  imageGenerationSuccess: 0
})

// 计算属性
const emptyMessage = computed(() => {
  if (Object.keys(searchCriteria.value).length > 0) {
    return '没有找到符合条件的图片，请尝试调整搜索条件'
  }
  return '还没有上传任何图片，点击上传按钮开始添加素材'
})

// 方法
const loadImages = async () => {
  // 防止重复请求
  if (isLoadingImages.value) {
    return
  }
  
  try {
    isLoadingImages.value = true
    loading.value = true
    
    const params = {
      page: currentPage.value - 1, // 后端从0开始
      size: pageSize.value,
      ...searchCriteria.value
    }
    
    let response: PaginatedResponse<ImageModel>
    
    if (searchCriteria.value.keyword || Object.keys(searchCriteria.value).length > 1) {
      // 使用搜索API
      response = await searchApi.advancedSearch(searchCriteria.value)
    } else {
      // 使用普通列表API
      response = await imageApi.getImages(params)
    }
    
    images.value = response.data || []
    
    // 更新分页信息
    if (response.pagination) {
      Object.assign(pagination, response.pagination)
    }
    
  } catch (error) {
    console.error('加载图片失败:', error)
    ElMessage.error('加载图片失败')
    images.value = []
  } finally {
    isLoadingImages.value = false
    loading.value = false
  }
}

const loadStatistics = async () => {
  // 防止重复请求
  if (isLoadingStats.value) {
    return
  }
  
  try {
    isLoadingStats.value = true
    
    const response = await imageApi.getImageStatistics()
    if (response.success && response.data) {
      Object.assign(statistics, response.data)
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  } finally {
    isLoadingStats.value = false
  }
}

const handleSearch = (criteria: SearchCriteria) => {
  searchCriteria.value = { ...criteria }
  currentPage.value = 1
  loadImages()
}

const handleGetSuggestions = async (keyword: string) => {
  try {
    const response = await searchApi.getSearchSuggestions(keyword)
    if (response.success && response.data) {
      searchFilterRef.value?.setSuggestions(response.data)
    }
  } catch (error) {
    console.error('获取搜索建议失败:', error)
  }
}

const handleLoadPopularTags = async () => {
  // 防止重复请求
  if (isLoadingTags.value) {
    return
  }
  
  try {
    isLoadingTags.value = true
    
    const response = await searchApi.getTagCloud()
    if (response.success && response.data) {
      popularTags.value = response.data
    }
  } catch (error) {
    console.error('加载热门标签失败:', error)
  } finally {
    isLoadingTags.value = false
  }
}

const handleImageClick = (image: ImageModel) => {
  const index = selectedImages.value.findIndex(img => img.id === image.id)
  if (index > -1) {
    selectedImages.value.splice(index, 1)
  } else {
    selectedImages.value.push(image)
  }
}

const handlePreview = (image: ImageModel) => {
  previewImage.value = image
  previewVisible.value = true
}

const handleGenerateText = (image: ImageModel) => {
  router.push({
    name: 'Generate',
    query: { imageId: image.id }
  })
}

const handleExpandImage = (image: ImageModel) => {
  router.push({
    name: 'Expand',
    query: { imageId: image.id }
  })
}

const handleDeleteImage = async (image: ImageModel) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除图片 "${image.originalName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await imageApi.deleteImage(image.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadImages()
      loadStatistics()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleTagClick = (tag: string) => {
  searchCriteria.value = {
    ...searchCriteria.value,
    tags: [tag]
  }
  currentPage.value = 1
  loadImages()
}

const handleShowAllTags = (image: ImageModel) => {
  currentImageTags.value = image.tags || []
  tagsVisible.value = true
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadImages()
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadImages()
}

const goToUpload = () => {
  router.push({ name: 'Upload' })
}

const selectAll = () => {
  selectedImages.value = [...images.value]
}

const clearSelection = () => {
  selectedImages.value = []
}

const batchGenerateText = () => {
  if (selectedImages.value.length === 0) return
  
  router.push({
    name: 'Generate',
    query: { 
      imageIds: selectedImages.value.map(img => img.id).join(',')
    }
  })
}

const batchExpandImages = () => {
  if (selectedImages.value.length === 0) return
  
  router.push({
    name: 'Expand',
    query: { 
      imageIds: selectedImages.value.map(img => img.id).join(',')
    }
  })
}

const batchDeleteImages = async () => {
  if (selectedImages.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedImages.value.length} 张图片吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const ids = selectedImages.value.map(img => img.id)
    const response = await imageApi.deleteImages(ids)
    
    if (response.success) {
      ElMessage.success(`成功删除 ${selectedImages.value.length} 张图片`)
      selectedImages.value = []
      loadImages()
      loadStatistics()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleClosePreview = () => {
  previewVisible.value = false
  previewImage.value = null
}

// 防止重复加载的标志
const isInitialized = ref(false)

// 生命周期
onMounted(async () => {
  if (isInitialized.value) {
    return
  }
  
  isInitialized.value = true
  
  try {
    // 并行加载，提高效率
    await Promise.all([
      loadImages(),
      loadStatistics(),
      handleLoadPopularTags()
    ])
  } catch (error) {
    console.error('Library 组件初始化失败:', error)
  }
})

// 监听路由变化，支持从其他页面跳转过来时的搜索
watch(() => router.currentRoute.value.query, (newQuery, oldQuery) => {
  // 只在查询参数真正变化时才触发，避免初始化时的重复请求
  if (newQuery.tag && newQuery.tag !== oldQuery?.tag) {
    handleTagClick(newQuery.tag as string)
  }
})
</script>

<style scoped>
.library-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.library-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-description {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0 0 30px 0;
}

.stats-bar {
  display: flex;
  justify-content: center;
  gap: 40px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 1.8rem;
  font-weight: 600;
  color: #409EFF;
}

.stat-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 5px;
}

.library-content {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 30px;
}

.library-sidebar {
  position: sticky;
  top: 20px;
  height: fit-content;
}

.library-main {
  min-width: 0;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.result-count {
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
}

.all-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.tag-item {
  cursor: pointer;
  transition: all 0.2s ease;
}

.tag-item:hover {
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .library-content {
    grid-template-columns: 280px 1fr;
    gap: 20px;
  }
  
  .stats-bar {
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .library-page {
    padding: 15px;
  }
  
  .library-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .library-sidebar {
    position: static;
  }
  
  .stats-bar {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 15px;
  }
  
  .toolbar-left {
    width: 100%;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }
}
</style>